<?
require_once('DataMediator.php');

class DataMediatorTest extends PHPUnit_Framework_TestCase {
	protected $c;
	protected function setUp() {
		$this->values= array(
			'stringField'=>'abc',
			'numberField'=>'123.45',
		);
		$this->dm= new DataMediator($this->values);
		$this->dm->setConverter('stringField','Text');
		$this->dm->setConverter('numberField','Number');
	}
	function testSetConverter() {
		$dm= new DataMediator($this->values);
		$c= $dm->setConverter('stringField','Text');
		$this->assertTrue($c instanceof TextConverter);
		$c= ConverterFactory::forName('Number');
		$this->assertSame($c,$dm->setConverter('numberField',$c));
	}
	function testGetConverter() {
		$dm= new DataMediator($this->values);
		$c= $dm->setConverter('stringField','Text');
		$this->assertSame($c,$dm->getConverter('stringField',$c));
	}
	function testAddValidator() {
		$v= $this->dm->addValidator('stringField','Required');
		$this->assertTrue($v instanceof RequiredValidator);
		$v= ValidatorFactory::forName('Required');
		$this->assertSame($v,$this->dm->addValidator('numberField',$v));
	}
	function testGetErrors() {
		$this->assertEquals(array(),$this->dm->getErrors());
		// set a converter which fails
		// set a converter which fails
		$this->dm->setConverter('stringField','Number');
		$errors= $this->dm->getErrors();
		$this->assertEquals(1,count($errors));
		$this->assertTrue($errors[0] instanceof DataMediatorError);
	}
	function testIsValid() {
		$this->assertTrue($this->dm->isValid());
		// set a converter which fails
		$this->dm->setConverter('stringField','Number');
		$this->assertFalse($this->dm->isValid());
	}
	function testGetFields() {
		$fields= $this->dm->getFields();
		$names= array('stringField','numberField');
		$this->assertEquals($names,array_keys($fields));
	}
	function testGetField() {
		$this->assertTrue($this->dm->getField('stringField') instanceof DataMediatorField);
	}
	function testGetWrongField() {
		$this->setExpectedException('InvalidArgumentException');
		$this->dm->getField('no_field');
	}
	function testGetAsString() {
		$this->assertSame('abc',$this->dm->getAsString('stringField'));
	}
	function testGetAsDatatype() {
		$this->assertSame(123.45,$this->dm->getAsDatatype('numberField'));
	}
}
